﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using JCTimes.DomainModel.Repository;
using JCTimes.EFRepository;
using JCTimes.EFRepository.Specification;

namespace JCTimes.EFRepository.RepositoryImpl
{
    public class BaseRepository<T> : IRepository<T> where T : class {
        //protected readonly JCTimesDbContext db = new JCTimesDbContext();

        [Inject]
        public JCTimesDbContext db { get; set; }

        public IQueryable<T> All {
            get {
                return db.Set<T>();
            }
        }

        public T Find(params object[] keys) {
            return db.Set<T>().Find(keys);
        }

        public T Find(Func<T, bool> filter) {
            return db.Set<T>().FirstOrDefault(filter);

        }

        public void Add(T model) {
            db.Set<T>().Add(model);
        }

        public void Delete(T model) {
            db.Entry(model).State = System.Data.EntityState.Deleted;
        }

        public void Update(T model) {
            db.Entry(model).State = System.Data.EntityState.Modified;
        }

        public int SaveChanges() {
            try {
                return db.SaveChanges();
            } catch (System.Data.Entity.Validation.DbEntityValidationException ex) {
                var errMsgs = ex.EntityValidationErrors
                               .SelectMany(e => e.ValidationErrors)
                               .Select(ve => string.Format("Property: {0}, ErrorMessage: {1}\r\n", ve.PropertyName, ve.ErrorMessage))
                               .Aggregate((result, each) => result += each);
                throw new Exception(errMsgs, ex);
            }
        }

        //public void Dispose() {
        //    db.Dispose();
        //}

        public IQueryable<U> GetList<U>() where U : class {
            return db.Set<U>();
        }
    }
}
